<template>
  <div class="course-platform">
      <!-- 顶部栏 -->
      <div class="top-bar">
          <div class="platform-title">智慧课程平台</div>
          <div class="nav-menu">
              <div class="nav-item" index="1" @click="handleNavClick('1')">我的课程</div>
              <div class="nav-item" index="2" @click="handleNavClick('2')">课程列表</div>
               <!-- 加这个 -->
              <div v-if="userInfo.role === 'student'" class="nav-item" :class="{ active: activeIndex === '3' }" @click="handleNavClick('3')">课程状态</div>
          </div>
          <div class="right-menu">
              <div class="right-menu-item" @click="handlePersonalCenter">个人中心</div>
              <div class="right-menu-item" @click="handleLogout">安全退出</div>
          </div>
      </div>

    <!-- 主要内容区 -->
    <div class="main-content">


      <!-- 个人中心页面 -->
      <PersonalCenter
        v-if="activeIndex === '4'"
        :userInfo="userInfo"
      />


       <!-- 我的课程页面 -->
      <div v-if="activeIndex === '1'" class="my-courses-page">
        <el-row :gutter="20">
          <!-- 左侧栏 -->
          <el-col :span="6">
            <!-- 个人信息卡片 -->
            <PersonalInfoCard :userInfo="userInfo" />

             <!-- 通知中心 -->
             <NotificationCenter
                :userRole="userInfo.role"
                :pendingAssignmentsCount="pendingAssignments.length"
                 @show-assignments="showPendingAssignments = true; fetchPendingAssignments()"
             />

             <!-- 在card外添加弹窗组件 -->
             <PendingAssignments
                v-model ="showPendingAssignments"
                :assignments="pendingAssignments"
             />


          </el-col>

          <!-- 右侧课程表 -->
            <el-col :span="18">
              <CourseSchedule
              :courses="courses"
              :currentSemester="currentSemester"
             />
            </el-col>
        </el-row>
      </div>


        <!-- 课程列表 --> <div v-if="activeIndex === '2'" class="course-list-container">
      <div class="semester-selector">
    <el-select
      v-model="selectedSemester"
      placeholder="请选择学期"
      @change="handleSemesterChange"
      style="margin-bottom: 20px; width: 200px; float: right;">
      <el-option
        v-for="item in availableSemesters"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-select>
  </div>
        <el-row :gutter="20">
            <el-col :span="8" v-for="course in courses" :key="course.id">
                <el-card :body-style="{ padding: '0px' }">
                    <div class="image-container">
                        <img :src="course.cover" class="image">
                    </div>
                    <div style="padding: 14px;"> <h3>{{ course.name }}</h3> <p>课程号: {{ course.id }}</p>
                    <div class="bottom clearfix"> <el-button type="text" class="button" @click="viewCourseDetail(course.id)">查看详情</el-button>
                    </div>
                </div> </el-card> </el-col>


         <!-- 创建课程卡片（仅对教师可见） -->
         <el-col :span="8" v-if="userInfo.role === 'teacher'">
    <el-card :body-style="{ padding: '0px' }">
      <div class="image-container" style="height: 147px; display: flex; align-items: center; justify-content: center;">
        <el-button type="primary" @click="showCreateDialog = true; fetchCourses() " >创建新课程</el-button>
      </div>
    </el-card>
  </el-col>
      </el-row>

    <!-- 创建课程表单（仅对教师可见） -->
     <CreateCourseDialog
    v-model="showCreateDialog"
    @course-created="handleCourseCreated"
  />

</div>

       <!-- 课程状态 （仅对学生可见）--><!-- 加这个 -->
      <div v-if="activeIndex === '3'" class="course-status-page">
        <h2>课程状态</h2>
        <el-table
          :data="coursestatus"
          style="width: 100%"
          border>
          <el-table-column
            type="index"
            label="序号"
            width="70"
            align="center">
          </el-table-column>
          <el-table-column
            prop="course_id"
            label="课程号"
            width="120"
            align="center">
          </el-table-column>
          <el-table-column
            prop="course_name"
            label="课程名称"
            min-width="200"
            align="center">
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            width="120"
            align="center">
          </el-table-column>
          <el-table-column
            prop="final_grade"
            label="最终成绩"
            width="120"
            align="center">
          </el-table-column>
          <el-table-column
            prop="completed_at"
            label="结课时间"
            width="180"
            align="center">
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import CourseTimeSelector from './CreateCourse/CourseTimeSelector.vue';
import PersonalCenter from "@/components/PersonalCenter/PersonalCenter.vue";
import CreateCourseDialog from "@/components/CreateCourse/CreateCourseDialog.vue";
import PendingAssignments from "@/components/notice/PendingAssignments.vue";
import NotificationCenter from "@/components/notice/NotificationCenter.vue";
import CourseSchedule from "@/components/CourseSchedule/CourseSchedule.vue";
import PersonalInfoCard from "@/components/PersonalInfoCard/PersonalInfoCard.vue";
import axios from "axios";
export default {
  name: 'CoursePlatform',
  components: {
     CourseSchedule,
    PersonalInfoCard,
    PendingAssignments,
    CourseTimeSelector,
    CreateCourseDialog,
    PersonalCenter,
    NotificationCenter
  },
  data() {
    return {
      pendingAssignments: [],
    showPendingAssignments: false,
        showCreateDialog: false,
        showCreateForm: false,
        newCourse: {
            id: '',
            semester: '',
            name: '',
            description: '',
            syllabus: '',
            time: '{}'
        },
      activeIndex: '1',
       userInfo: {
        id: '',
        name: '',
        role: '',
        email: ''
      },
      courses: [],
      coursestatus: [],
      unreadMessages: 0,
      selectedSemester: '', // 当前选中的学期
      availableSemesters: [], // 可选择的学期列表
      unreadCourseNotices: 46,
    };
  },
  computed: {
    currentSemester() {
      return this.getCurrentSemester();
    }
  },
  methods: {
      handleNavClick(index) {
          this.activeIndex = index;
          switch(index) {
              case '1':
                  this.fetchCourses();
                  break;
              case '2':
                  this.fetchCourses();
                  this.showCreateForm = false; // 重置创建表单的显示状态
                  break;
              case '3'://加这个
                  this.fetchCourseStatus();
                  break;
          }
      },
    viewCourseDetail(courseId) {
      this.$router.push(`/course/${courseId}`);
    },
    handlePersonalCenter() {
        this.activeIndex = '4';
    },
    getCurrentSemester() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1; // JavaScript 月份从 0 开始

      if (month >= 2 && month <= 7) {
        return `${year}-2000`;// 第二学期
      } else {
        return `${year}-1000`; // 第一学期
      }
    },
     // 获取可选择的学期列表
  getAvailableSemesters() {
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth() + 1;
    const semesters = [];

    // 判断当前是第一学期还是第二学期
    if (currentMonth >= 2 && currentMonth <= 7) {
      // 当前是第一学期 (2-7月)

      semesters.push({
        label: `${currentYear}-${currentYear + 1}学年第二学期`,
        value: `${currentYear}-2000`
      });
      // 上一个学期是当年的第一学期
      semesters.push({
        label: `${currentYear}-${currentYear + 1}学年第一学期`,
        value: `${currentYear}-1000`
      });
    } else {
      // 当前是第二学期 (8-1月)
      semesters.push({
        label: `${currentYear}-${currentYear + 1}学年第一学期`,
        value: `${currentYear}-1000`
      });
      // 上一个学期是上一年的第二学期
      semesters.push({
        label: `${currentYear - 1}-${currentYear}学年第二学期`,
        value: `${currentYear - 1}-2000`
      });
    }

    this.availableSemesters = semesters;
    // 设置默认选中当前学期
    this.selectedSemester = semesters[0].value;
  },
     async fetchUserInfo() {
      try {
        const response = await axios.get('/backend/api/account/profile/', { withCredentials: true });
        this.userInfo = {
          id: response.data.id,
          name: response.data.username,
          role: response.data.role,
          email: response.data.email,
        };
          this.isTeacher = response.data.role === 'teacher';
      } catch (error) {
        console.error('获取用户信息失败:', error);
        this.error = '获取用户信息失败';
      }
    },
    async handleCourseCreated() {
      try {
        // 关闭创建对话框
        this.showCreateDialog = false;

        // 显示成功提示
        this.$message({
          type: 'success',
          message: '课程创建成功！'
        });

        // 重新获取课程列表
        await this.fetchCourses();
      } catch (error) {
        console.error('刷新课程列表失败:', error);
        this.$message({
          type: 'error',
          message: '刷新课程列表失败，请手动刷新页面'
        });
      }
    },
    async fetchCourses() {
    const response = await axios.post('/backend/api/course/courses/',
      { semester: this.selectedSemester || this.currentSemester },
      { withCredentials: true }
    );
    this.courses = response.data;
  },

  // 处理学期选择变化
  handleSemesterChange(value) {
    this.selectedSemester = value;
    this.fetchCourses();
  },

    //查看课程状态
    // 加这个
async fetchCourseStatus() {
  try {
    const response = await axios.get(`/backend/api/course/student/courses/${this.currentSemester}/`, {
      withCredentials: true
    });
    this.coursestatus = response.data;
  } catch (error) {
    console.error('获取课程状态失败:', error);
  }
},
    //退出登录
    async handleLogout() {
      try {
        const response = await axios.post('/backend/api/account/logout/', {},
          { withCredentials: true }
        );

        if (response.data.message === "Logged out successfully") {
          this.$message({
            type: 'success',
            message: '退出登录成功'
          });
          // 重定向到登录页面
          this.$router.push('/login');
        }
      } catch (error) {
        console.error('退出登录失败:', error);
        this.$message({
          type: 'error',
          message: '退出登录失败，请重试'
        });
      }
    },
    //获取未交作业
    async fetchPendingAssignments() {
  try {
    const response = await axios.get('/backend/api/assignment/pending_assignments/');
    this.pendingAssignments = response.data;
  } catch (error) {
    console.error('获取未交作业失败:', error);
  }
},

  },
  mounted() {
    document.title = "智慧课程平台"
    this.fetchUserInfo();
     this.getAvailableSemesters();
    this.fetchPendingAssignments();
    this.fetchCourses().then(() => {
    this.fetchCourseStatus();

  });
  }
}
</script>

<style scoped>
.course-status-page {
    max-width: 1200px;
    margin: 40px auto;
    padding: 30px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 5px 12px rgba(0, 0, 0, 0.1);
}

.course-status-page h2 {
    margin-bottom: 30px;
    color: #303133;
    font-size: 24px;
    text-align: center;
}
.el-table {
    font-size: 18px; /* 进一步增大基础字体大小 */
    border: 9px solid #EBEEF5; /* 添加表格外边框 */
}
.right-menu {
  display: flex;
  align-items: center;
  margin-left: auto; /* 确保右侧对齐 */
}

.right-menu-item {
  padding: 0 15px;
  height: 60px;
  line-height: 60px;
  cursor: pointer;
  color: white;
  transition: all 0.3s;
}

.right-menu-item:hover {
  color: #ffd04b;
  background-color: rgba(64, 158, 255, 0.1);
}
.el-card {
  margin-bottom: 20px;
}

.image-container {
  width: 100%;
  padding-top: 56.25%; /* 16:9 Aspect Ratio */
  position: relative;
  overflow: hidden;
}
.el-table .cell {
  white-space: pre-line;
}
.image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}


.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.about-content {
  padding: 20px;
  line-height: 1.6;
  text-align: justify;
}
.course-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 50px 50px 0;
}

.el-row {

  margin-bottom: 20px;
}

.el-col {
    padding: 0 15px;
  margin-bottom: 20px;
}

.my-courses-page {
  padding: 50px;
}

.el-badge {
    display: block;
}

.el-badge .el-badge__content {
    font-size: 16px;
    height: 24px;
    line-height: 24px;
    padding: 0 8px;
}
.top-bar {
    display: flex;
    align-items: center;
    background-color: #409EFF;
    color: white;
    padding: 15px 40px; /* 增加上下内边距 */
    font-size: 18px; /* 增加整体字体大小 */
}

.platform-title {
    font-size: 30px; /* 增加标题字体大小 */
    font-weight: bold;
    margin-right: 30px; /* 增加右边距 */
}
.nav-menu {
    display: flex; /* 确保水平排列 */
    align-items: center; /* 垂直居中对齐 */
    gap: 20px; /* 在导航项之间保持一定间距 */
}

.nav-item {
    cursor: pointer;
    font-size: 18px; /* 增加导航项字体大小 */
    padding: 5px 10px; /* 增加可点击区域 */
}

.nav-item:hover {
    color: #ffd04b;
}

.personal-center {
    margin-left: auto;
    cursor: pointer;
    font-size: 18px; /* 增加个人中心字体大小 */
    padding: 5px 10px; /* 增加可点击区域 */
}

.semester-selector {
  margin-bottom: 20px;
  overflow: hidden;
}

</style>